import { User } from '../pojo/user.js'
import { SQL } from '../sql.js'
import { db } from '../index.js'

class UserDao {    
    constructor() {
        this.tableName = 'users'
        this.sql = new SQL({ tableName: this.tableName })
    }

    /**
     * 添加用户
     * @param {User} user 
     */
    insert(user) {
        const { sql, params } = this.sql.insert(user)
        return db.database.prepare(sql).run(...params).lastInsertRowid
    }

    /**
     * 根据 id 查找用户
     * @param {undefined | number | number[]} ids 
     */
    query(ids) {
        const idsIsArray = Array.isArray(ids)
        if (!ids || idsIsArray) {
            const sqlSyntax = this.sql.select(null, idsIsArray ? { conditions: `id in (${ids.join(',')})` } : null)
            const users = db.database.prepare(sqlSyntax).all() 
            return users.map(user => new User(user))
        }
        const sqlSyntax = this.sql.select(null, { conditions: `id = ?` })
        const user = db.database.prepare(sqlSyntax).get(ids)
        return user ? new User(user) : null
    }

    queryWithConditions(conditions) {
        const sqlSyntax = this.sql.select(null, { conditions })
        return db.database.prepare(sqlSyntax).all().map(user => new User(user))
    }
}

export const userDao = new UserDao()
